<?php
namespace Admin\Model;
use Think\Model;
class LinkModel extends Model{
	protected $_validate = array(
		array('name','require','属性名称！'),    		
	);
	
	public function index(){
		$info = $this -> order('sort desc,id desc') -> select();
		return $info;
	}
				
	public function addDo(){
		if(!empty($_FILES['pic']['name'])){
			$info = $this -> upFile();
			if($info['msg'] == 0){
				echo $info['info'];
			}
			if($info['msg'] == 1){
				$data['pic'] = $info['info']['pic']['savepath'].$info['info']['pic']['savename'];
			}
		}else{
			unset($_POST['pic']);
		}
		$data['name'] = I('name');
		$data['sort'] = I('sort');
		$data['url'] = I('url');
		$info = $this -> add($data);
		return $info;
	}	
				
	public function edit(){
		$id = I('id');
		$info = $this -> where('id='.$id)->find();	
		return $info;
	}
	
	public function editDo(){
		if(!empty($_FILES['pic']['name'])){
			$pic = $this -> where(array('id'=>I('id','','intval')))->field('id,pic')->find();
			$url = './'.$pic['pic'];
			if(file_exists($url)){
				unlink($url);
			}
			$info = $this -> upFile();
			if($info['msg'] == 0){
				echo $info['info'];
			}
			if($info['msg'] == 1){
				$data['pic'] = $info['info']['pic']['savepath'].$info['info']['pic']['savename'];
			}
		}else{
			$data['pic'] = I('pic0');
		}
		$data['name'] = I('name');
		$data['sort'] = I('sort');
		$data['url'] = I('url');
		$data['id']    =(I('id'));
		$this ->save($data);
		return true;
	}	
				
	public function del(){
		$id = I('id');
		$pic = $this -> where(array('id' => $id)) -> find();
		$Pic = $pic['pic'];
		if(isset($Pic)){
			$url = './'.$Pic;
			if(file_exists($url)){
				unlink($url);
			}
		}
		$info = $this -> where(array('id' => $id)) -> delete();
		return $info;
	}
	
	public function sorts(){
		foreach($_POST as $k => $v){
			$info = $this -> where(array('id' => $k)) -> data(array('sort' => $v)) -> save();
		}
		return $info;
	}					
					
	public function upFile(){
		$upload = new \Think\Upload();                            // 实例化上传类
		$upload -> maxSize   = 3*1024*1024 ;                      // 设置附件上传大小
		$upload -> exts      = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload -> rootPath  = './';                              // 文件上传保存的根路径
		$upload -> savePath  = 'Uploads/Link/';             // 设置附件上传目录
		$upload -> autoSub   = false;                             //自动使用子目录保存上传文件 默认为true
		$upload -> saveName  = 'uniqid';		
		// 上传文件 
		$info   =   $upload->upload();
		if(!$info) {                  		// 上传错误提示错误信息    
			$pic = array(
				'msg' => 0,
				'info' => $upload->getError(),
			);
		}else{								// 上传成功 获取上传文件信息 
			$pic = array(
				'msg' => 1,
				'info' => $info,		
			);
		}
		return $pic;	
	}				
					
}